<template>
  <div class="wrap moniter-table">
    <div class="tips" v-if="$store.state.session.user.type === 'agent'">{{$t('monitor.tips')}}</div>
    <div style="margin-top: 36px;"></div>
    <affix :label="$t('monitor.callNumMonitorList')" v-show="filter.phoneServiceNos" :monitor="true" :moniterFlag="'call'" :showFlag="filter.callFl" @open="open">
      <div class="con" v-show="filter.callFl">
        <div class="tip">{{$t('monitor.concurrent')}}<span class="concurrent-num" data-v-7moor>{{concurrent}}</span></div>
        <table class="el-table el-table--striped el-table--enable-row-hover" border="0" cellspacing="0">
          <thead>
          <tr>
            <th><div class="cell" v-once>{{$t('monitor.serviceNum')}}</div></th>
            <th><div class="cell" v-once>{{$t('monitor.externalCallToday')}}</div></th>
            <th><div class="cell" v-once>{{$t('monitor.externalCallTodayMiss')}}</div></th>
            <th><div class="cell" v-once>{{$t('monitor.externalCallTodayAnswer')}}</div></th>
            <th><div class="cell" v-once>{{$t('monitor.todayConcurrAccessNum')}}</div></th>
          </tr>
          </thead>
          <tbody class="el-table__body">
          <!--<tr v-for="one in phoneServiceNos" :key="one.serviceNo">-->
            <!--<td>{{one.serviceNo}}</td>-->
            <!--<td>{{one.inCalls}}</td>-->
            <!--<td>{{one.inLost}}</td>-->
            <!--<td>{{one.inComplete}}</td>-->
            <!--<td>{{one.inLimit}}</td>-->
          <!--</tr>-->
          <tr-common  v-for="one in phoneServiceNos" :key="one.serviceNo" :one="one" :header="header.callNum"></tr-common>
          </tbody>
        </table>
      </div>
    </affix>
    <affix :label="$t('monitor.CallSkillMonitorList',{waitCountTotal})" :moniterFlag="'callSkill'" :monitor="true" :showFlag="filter.callSkillFl" @open="open" v-show="filter.phoneQueues">
      <table class="el-table el-table--striped el-table--enable-row-hover" border="0" cellspacing="0" v-show="filter.callSkillFl">
        <thead>
        <tr>
          <th><div class="cell" v-once>{{$t('monitor.skillGroupName')}}</div></th>
          <th><div class="cell" v-once>{{$t('monitor.spareAgent')}}</div></th>
          <th><div class="cell" v-once>{{$t('monitor.checkInAgent')}}</div></th>
          <th><div class="cell" v-once>{{$t('monitor.queueNumber')}}</div></th>
          <th><div class="cell" v-once>{{$t('monitor.connectCallNumToday')}}</div></th>
        </tr>
        </thead>
        <tbody class="el-table__body">
        <!--<tr v-for="one in phoneQueues" :key="one._id">-->
          <!--<td>{{one.queueName}}</td>-->
          <!--<td>{{one.idleAgentCount}}</td>-->
          <!--<td>{{one.totalAgentCount}}</td>-->
          <!--<td :style="{color:one.queueWaitCount > 0 ? 'red': ''}">-->
            <!--{{one.queueWaitCount}}-->
          <!--</td>-->
          <!--<td>{{one.linkCalls}}</td>-->
        <!--</tr>-->
        <tr-common  v-for="one in phoneQueues" :key="one._id" :one="one" :header="header.callSkill"></tr-common>
        </tbody>
      </table>
    </affix>
    <affix :label="$t('monitor.outCallMonitorList')" :moniterFlag="'outCall'" :monitor="true" :showFlag="filter.outCallFl" @open="open" v-show="filter.accountCalls">
      <table class="el-table el-table--striped el-table--enable-row-hover" border="0" cellspacing="0" v-show="filter.outCallFl">
        <thead>
        <tr>
          <th><div class="cell" v-once>{{$t('monitor.outCallSum')}}</div></th>
          <th><div class="cell" v-once>{{$t('monitor.outCallSuccess')}}</div></th>
        </tr>
        </thead>
        <tbody class="el-table__body">
        <tr v-for="one in phone_accountCalls" :key="one.pbx">
          <td>{{one.outCalls}}</td>
          <td>{{one.outComplete}}</td>
        </tr>
        </tbody>
      </table>
    </affix>
    <!--<h3 class="title"><span class="sign"></span><span class="text">{{$t('monitor.agentMonitorList')}}</span></h3>-->
    <affix :label="$t('monitor.agentMonitorList')" :monitor="true" :moniterFlag="'agent'" :showFlag="filter.agentFl" @open="open" v-show="filter.AgentPeer">

      <div class="Seats" v-show="filter.agentFl">
        <el-row class="agnet-search">
          <!--<el-col :span="1" class="search-label">{{$t('public.agent')}}：</el-col>-->
          <!--<el-col :span="5">-->
            <!--<el-select size="mini" v-model="agent" :placeholder="$t('public.pleasePick')" @change="monitorSearch" filterable>-->
              <!--<el-option-->
                      <!--label="全部"-->
                      <!--value="">-->
              <!--</el-option>-->
              <!--<el-option-->
                      <!--v-for="item in allAgent"-->
                      <!--:label="item.displayName + '['+ item.exten + ']'"-->
                      <!--:value="item._id">-->
              <!--</el-option>-->
            <!--</el-select>-->
          <!--</el-col>-->
          <!--<el-col :span="3">-->
            <!--<div class="checkbox-wrap">-->
              <!--<el-checkbox v-model="includeSubordinate" @change="monitorSearch">{{$t('public.includeSubordinate')}}</el-checkbox>-->
            <!--</div>-->
          <!--</el-col>-->
          <el-col :span="7">
            <div class="search-label fl">{{$t('monitor.agentState')}}：</div>
            <el-select size="mini" v-model="state" @change="monitorSearch" :placeholder="$t('public.pleasePick')">
              <el-option
                      v-for="(item,index) in phoneBarStauts"
                      :label="item.value"
                      :key="index"
                      :value="item.key">
              </el-option>
            </el-select>
          </el-col>
          <div class="clear10"></div>
        </el-row >
        <el-row>
          <el-col :span="21">
            &nbsp;
          </el-col>
          <el-col :span="3" class="fr">
            <p class="search-label record-num">
              {{$t('monitor.totalRecord', {count: agentCount})}}
            </p>
          </el-col>
          <div class="clear10"></div>
        </el-row>
        <table class="el-table el-table--striped el-table--enable-row-hover" border="0" cellspacing="0">
          <thead>
            <tr>
              <th v-for="item in headOptionsNoShow" :key="item.name" :class="{ ascending: (item.name === sortObj.name)&&(sortObj.type === 'up'),descending: (item.name === sortObj.name)&&(sortObj.type === 'down') }"><div class="cell" @click.stop="sort(item.name)" >{{item.displayname}}<span class="caret-wrapper" v-if="item.name !== 'answerStyle'" ><i class="sort-caret ascending"></i><i class="sort-caret descending"></i></span></div></th>
              <th v-for="item in monitorHeader" :key="item.name" v-show="item.show === true" :class="{ ascending: (item.name === sortObj.name)&&(sortObj.type === 'up'),descending: (item.name === sortObj.name)&&(sortObj.type === 'down') }"><div class="cell" @click.stop="sort(item.name)">{{item.displayname}}<span class="caret-wrapper" ><i class="sort-caret ascending"></i><i class="sort-caret descending"></i></span></div></th>
              <th><div class="cell">{{$t('monitor.operate')}}</div></th>
            </tr>
          </thead>
          <tbody class="el-table__body">
            <tr-agent
              :one="one"
              v-for="one in monitorPeerDisplay"
              :key="one.userId"
              :monitorHeader="monitorHeader"
              v-show="one.isShow"
              @ctiUiListen="ctiUiListen"
              @ctiUiEndListen="ctiUiEndListen"
              @ctiUiForceHangup="ctiUiForceHangup"
              @ctiUiLoot="ctiUiLoot"
              @ctiUiKick="ctiUiKick"
              @ctiUiPick="ctiUiPick"
            ></tr-agent>
          </tbody>
        </table>
      </div>
    </affix>
    <!--<header-option :show="isShow" :option="headOptionsShow"  :noDrag="headOptionsNoShow" type="im_monitor_agent" v-on:close="close"></header-option>-->
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('public.tip')" :visible.sync="dialogFormVisible">
      <div class="moniter-dialog">
        <div class="dialog-title">{{$t('monitor.noCheckIn')}}</div>
        <el-row :gutter="15">
          <el-col :span="20">
            <el-form :model="form" :label-position="'left'" :rules="rules" ref="form" label-width="180px">
              <el-form-item :label="formLabel" prop="mobile">
                <el-input size="mini" v-model.trim="form.mobile" auto-complete="off"></el-input>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="4"></el-col>
        </el-row>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" type="warning" @click="saveLocalNumForPhonePick">{{$t('monitor.saveAndCheckIn')}}</el-button>
        <el-button class="primary_btn" @click="dialogFormVisible = false">{{$t('public.cancel')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
//  let todayIncoming = $t('monitor.todayIncoming')
  import {getCache, deepClone, checkHideTel} from '@/utils/m7Utils.js'
  import {showCountDown} from '@/utils/workflowUtils.js'
  import { checkform } from '@/utils/validate'
  import {ctiUicontrolMonitor, ctiUiDisplayStatus, ctiUiGetQueuePeer, ctiUiDisplayExtenType} from '@/utils/monitor.js'
  import affix from './../../ui-modules/affix/Affix.vue'
  import trAgent from './TrAgent.vue'
  import trCommon from './TrCommon.vue'
  export default {
    name: 'monitorTableTemp',
    data () {
      let validate1 = (rule, value, callback) => {
        let match = checkform(value, 'Number')
        if (match) {
          callback(new Error(this.$t(match)))
        } else {
          callback()
        }
      }
      return {
        showFlag: true,
        concurrent: 0,
        visible2: false,
        agent: '',
        agentArray: [], // 显示的坐席
        allAgent: [],
        allState: {},
        state: '',
        includeSubordinate: false,
        selectState: [],
        monitorPeerDisplay: [],
        timer: '',
        isShow: false,
        headOptionsShow: {},
        dialogFormVisible: false,
        formLabel: '',
        form: {
          _id: '',
          mobile: ''
        },
        scope: 'noScope',
        headOptionsNoShow: [{'name': 'agentName', displayname: this.$t('public.agent'), 'order': 1, 'show': true}, {'name': 'agentNo', displayname: this.$t('public.jobNumber'), 'order': 2, 'show': true}, {'name': 'version', displayname: this.$t('monitor.agentVersion'), 'order': 3, 'show': true},{'name': 'answerStyle', displayname: this.$t('monitor.answerMode'), 'order': 4, 'show': true}, {'name': 'state', displayname: this.$t('public.state'), 'order': 5, 'show': true}],
        // 电话技能组排队总数
        waitCountTotal: 0,
        agentCount: 0,
        sortObj: {
          name: '',
          type: '',
          num: 0
        },
        rules: {
          mobile: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'},
            {validator: validate1, trigger: 'blur'}
          ]
        },
        header: {
          callNum: [{prop: 'serviceNo'}, {prop: 'inCalls'}, {prop: 'inLost'}, {prop: 'inComplete'}, {prop: 'inLimit'}],
          callSkill: [{prop: 'queueName'}, {prop: 'idleAgentCount'}, {prop: 'totalAgentCount', tooltip: true}, {prop: 'queueWaitCount', color: 'red'}, {prop: 'linkCalls'}]
        },
        phoneQueues: [],
        phoneServiceNos: [],
        sumNum: Object.keys(window.phone_peers).length
      }
    },
    props: {
      filter: {type: Object, default: function () { return {} }}
    },
    computed: {
      currentAgentState () {
        return this.$store.state.monitor.agentStateChange.random || 0
      },
      phone_accountCalls () {
        let data = this.$store.state.cti.globalLet.phone_accountCalls
        let array = []
        for (var i in data) {
          array.push(data[i])
        }
        return array
      },
      monitorHeader () {
         // 老数据没有监控类型
        if (!this.filter.monitorType) {
          return this.headOptionsShow.Config || []
        } else {
          let header = this.filter.AgentHeadConfig || {}
          let data = deepClone(header.Config) || []
          data.splice(0, 5)
          return data
        }
      },
      phoneBarStauts () {
        return this.phoneBarStatusArr('all')
      },
      phoneBarStautsOnline () {
        return this.phoneBarStatusArr()
      }
    },
    components: {
      affix,
      trAgent,
      trCommon
    },
    watch: {
      sumNum () {
        this.fetchData()
      },
      '$store.state.cti.phoneQueuesChange.random' () {
        this.fetchQueuesData()
      },
      'filter._id' () {
        this.phoneServiceNosData()
        this.fetchQueuesData()
        this.monitorSearch()
      },
      currentAgentState () {
        let phonePeer = window.phone_peers
        this.sumNum = Object.keys(phonePeer).length
        let newValue = this.$store.state.monitor.agentStateChange.userIdtemp
        for (let i in newValue) {
          let newV = newValue[i]
          if (this.scope === 'noScope') {
          } else {
            if (this.scope.indexOf(newV) === -1) {
              continue
            }
          }
          let index = -1
          for (let i = 0; i < this.monitorPeerDisplay.length; i++) {
            if (this.monitorPeerDisplay[i].userId === newV) {
              index = i
              break
            } else {
              index = -1
            }
          }
          if (index === -1) {
//          if (phonePeer[newV]) {
//            let data = this.monitorPeerNew(im[newV], phonePeer[newV], 'create', newV)
//            data.isShow = true
//            this.monitorPeerDisplay.push(data)
//          }
          } else {
            let data = this.monitorPeerNew(null, phonePeer[newV], 'update', newV)
            let oldShow = this.monitorPeerDisplay[index].isShow
            let newShow = this.filterAgent(data)
            if (oldShow === newShow) {
              data.isShow = oldShow
            } else if (newShow) {
              data.isShow = newShow
              this.agentCount++
            } else {
              data.isShow = newShow
              this.agentCount--
            }
            // this.monitorPeerDisplay.splice(index, 1, data)
            this.update(this.monitorPeerDisplay[index], data)
          }
        }
        this.$store.commit('AGENT_STATE_CHANGE', 'deleteTemp')
      },
      '$store.state.cti.serviceNoChange.random' () {
        this.phoneServiceNosData()
      }
    },
    methods: {
      update (target, data) {
        for (const key in data) {
          if (key in target) {
            target[key] = data[key]
          } else {
            this.$set(target, key, data[key])
          }
        }
      },
      phoneServiceNosData () {
        let data = window.phone_serviceNos
        let array = []
        if (this.filter.phoneServiceNos) {
          let filter = this.filter.phoneServiceNosArr || []
          filter.forEach((i) => {
            let data1 = {}
            if (data[i]) {
              Object.assign(data1, data[i])
              if (data[i].displayName !== '') {
                data1.serviceNo = data[i].serviceNo + '(' + data[i].displayName + ')'
              }
              array.push(data1)
            }
          })
        }
        this.phoneServiceNos = array
      },
      fetchQueuesData () {
        let data = window.phone_queues
        let array = []
        this.waitCountTotal = 0
        if (this.filter.phoneQueues) {
          let filter = this.filter.phoneQueuesArr || []
          filter.forEach((i) => {
            var data1 = {}
            if (data[i]) {
              Object.assign(data1, data[i])
              this.waitCountTotal += data[i].queueWaitCount
              if (data[i].totalAgentCount !== 0) {
                data1.totalAgentCount = data1.totalAgentCount + ctiUiGetQueuePeer(data[i], this.$store.state)
              }
              let linkCalls = data1.totalCalls - data1.abadonedCalls
              data1.linkCalls = linkCalls > 0 ? linkCalls : 0
              data1._id = i
              array.push(data1)
            }
          })
        }
        this.phoneQueues = array
      },
      open (data) {
        console.log(this.filter)
        console.log(data)
        if (data.moniterFlag === 'call') {
          this.filter.callFl = data.flag
        } else if (data.moniterFlag === 'multiChannel') {
          this.filter.multiChannelFl = data.flag
        } else if (data.moniterFlag === 'callSkill') {
          this.filter.callSkillFl = data.flag
        } else if (data.moniterFlag === 'multiChannelSkill') {
          this.filter.multiChannelSkillFl = data.flag
        } else if (data.moniterFlag === 'outCall') {
          this.filter.outCallFl = data.flag
        } else if (data.moniterFlag === 'agent') {
          this.filter.agentFl = data.flag
        }
      },
      filterAgent (item) {
        // 座席条件
        let filter1 = false
        // 状态条件
        let filter2 = false
        if (this.agentArray.indexOf(item.userId) !== -1) {
          filter1 = true
        }
        if (this.state === '') {
          filter2 = true
        } else if (this.state === this.$t('monitor.online')) {
          this.phoneBarStautsOnline.forEach((one) => {
            if (item.state && one.value === item.state.content) {
              filter2 = true
            }
          })
        } else {
          if (item.state && this.state === item.state.content) {
            filter2 = true
          } else {
            filter2 = false
          }
        }
        if (filter1 && filter2) {
          return true
        } else {
          return false
        }
      },
      monitorSearch () {
        if (this.filter.currentQueue.length === 0 && this.filter.selectedAgentList.length === 0) {
          this.agentArray = this.allAgent.map(item => item._id)
        } else {
          this.agentArray = this.filter.AgentPeerArr || []
        }
        this.agentCount = 0
        for (let i in this.monitorPeerDisplay) {
          if (this.filterAgent(this.monitorPeerDisplay[i])) {
            this.monitorPeerDisplay[i].isShow = true
            this.agentCount++
          } else {
            this.monitorPeerDisplay[i].isShow = false
          }
        }
      },
      scopeAgents () {
        let session = this.$store.state.session
        if (session.user.type !== 'admin' && session.user.scope.call !== 'all') {
          let lowUsers = session.user.moduleUsers.call || []
          return lowUsers
        } else {
          return 'noScope'
        }
      },
      sort (name) {
        if (name === 'answerStyle') {
          return
        }
        if (this.sortObj.name !== name) {
          this.sortObj.num = 0
        }
        this.sortObj.name = name
        if (this.sortObj.num % 2) {
          this.sortObj.type = 'down'
        } else {
          this.sortObj.type = 'up'
        }
        this.sortObj.num++
        this.monitorPeerDisplay.sort((a, b) => {
          if (this.sortObj.type === 'down') {
            return this.sortMethod(a, b, this.sortObj.name)
          } else {
            return this.sortMethod(b, a, this.sortObj.name)
          }
        })
      },
      sortMethod (a, b, name, type) {
        let x = ''
        let y = ''
        if (name === 'state') {
          if (a.state.content) {
            x = a.state.content.replace(/\s+/g, '')
          }
          if (b.state.content) {
            y = b.state.content.replace(/\s+/g, '')
          }
        } else {
          x = a[name]
          y = b[name]
        }
        if (name === 'allBusyTime' || name === 'allVacaTime' || name === 'allOnlineTime' || name === 'allIdleTime' || name === 'stateTime' || name === 'dealingTime' || name === 'DealingTime' || name === 'agentName' || name === 'state' || name === 'queueName' || name === 'autoStatus' || name === 'mailAutoStatus' || name === 'version') {
          return x.localeCompare(y)
        } else {
          return x - y
        }
      },
      ctiUiListen (data) {
        let peer = window.phone_peers[data.userId]
        if (peer == null) {
          this.$message.error(this.$t('cti.chanSpyFailed'))
          return
        }
        if (this.$store.state.cti.globalLet.phone_data.busyType === '0') {
          this.$message.error(this.$t('cti.configPhoneBusy'))
          return
        }
        if (this.$store.state.cti.globalLet.phone_data.extenType === 'none') {
          this.$message.error(this.$t('cti.spyWithLoginTypes'))
          return
        }
        if (peer.userId === this.$store.state.cti.globalLet.phone_data.userId) {
          this.$message.error(this.$t('cti.noSpyUserSelf'))
          return
        }
        if (peer.callStatus !== 'webcall' && peer.callStatus !== 'inner' &&
          peer.callStatus !== 'normal' && peer.callStatus !== 'dialout' &&
          peer.callStatus !== 'dialTransfer' && peer.callStatus !== 'transfer') {
          this.$message.error(this.$t('cti.statusForbidSpy'))
          return
        }
        this.$store.dispatch('phoneListen', data.channel).then((response) => {
          for (let i = 0; i < this.monitorPeerDisplay.length; i++) {
            let item = this.monitorPeerDisplay[i]
            if (item.userId === data.userId) {
              this.monitorPeerDisplay[i].operate.buttonState.listen = {disabled: true, show: false}
              this.monitorPeerDisplay[i].operate.buttonState.loot = {disabled: true, show: false}
            }
          }
        })
      },
      ctiUiEndListen (data) {
        this.$store.dispatch('phoneHangup').then((response) => {
          for (let i = 0; i < this.monitorPeerDisplay.length; i++) {
            let item = this.monitorPeerDisplay[i]
            if (item.userId === data.userId) {
              this.monitorPeerDisplay[i].operate.buttonState.listen = {disabled: false, show: true}
              this.monitorPeerDisplay[i].operate.buttonState.loot = {disabled: false, show: true}
            }
          }
        })
      },
      ctiUiForceHangup (data) {
        if (data.pbx === this.$store.state.cti.globalLet.phone_data.pbx_in_ip) {
          this.$store.dispatch('phoneHangupChannel', data.channel).then((response) => {
          })
        } else {
          this.$store.dispatch('phoneHangupChannelFromPbx', data).then((response) => {
          })
        }
      },
      ctiUiLoot (data) {
        this.$store.dispatch('phoneLoot', data.linkedChannel).then((response) => {
        })
      },
      ctiUiKick (data) {
        this.$store.dispatch('phoneKick', data.userId).then((response) => {
        })
      },
      ctiUiPick (data, extenType) {
        let dataPick = {
          userId: data.userId,
          extenType: extenType
        }
        this.$store.dispatch('phonePick', dataPick).then((response) => {
          if (response != null && !response.Local) {
            let userInfo = window.phone_peers[data.userId]
            let name = userInfo.DisplayName + '[' + userInfo.exten + ']'
            this.formLabel = this.$t('monitor.setNumber', {name})
            this.form._id = data.userId
            this.form.mobile = ''
            this.dialogFormVisible = true
          }
        })
      },
      saveLocalNumForPhonePick () {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$store.dispatch('saveLocalNumForPhonePick', this.form).then((response) => {
              this.dialogFormVisible = false
              this.form._id = ''
              this.form.mobile = ''
            })
          }
        })
      },
      change (selectAgent) {
        var agents = []
        let agentList = this.allAgent
        if (selectAgent === '') {
          this.allAgent.forEach(function (item) {
            agents.push(item._id)
          })
        } else {
          agents.push(selectAgent)
        }
        if (this.includeSubordinate) {
          let getAgent = function (pid) {
            for (var i = 0; i < agentList.length; i++) {
              var obj = agentList[i]
              if (obj.parentId && obj.parentId === pid) {
                agents.push(obj._id)
                getAgent(obj._id)
              }
            }
          }
          getAgent(selectAgent)
        }
        return agents
      },
      monitorPeerNew (im, phone, flag, user) {
        let ctiUiDesc = this.$store.state.cti.globalLet._cti_ui_desc
        let phoneData = this.$store.state.cti.globalLet.phone_data
        let onePeer = phone
        if (!onePeer) {
          return {}
        }
        let agentName = onePeer.DisplayName ? onePeer.DisplayName : ''
        // userId取key值，防止两个座席绑定同一个sipNum时，一直push的问题
        let userId = user
        let agentNo = onePeer.exten
        let answerStyle = ctiUiDisplayExtenType(onePeer)
        let state = ctiUiDisplayStatus(onePeer, ctiUiDesc, phoneData)
        var date = new Date()
        let statusTime = onePeer.statusTime || {}
        let timeDiff = onePeer.statusTimestamp ? (date.getTime() - onePeer.statusTimestamp) : 0
        // 总置忙时长
        let busySum = Number(statusTime.AllBusyTime) || 0
        // 总小休时长
        let restSum = Number(statusTime.AllVacaTime) || 0
        // 总在线时长
        let onlineSum = Number(statusTime.AllOnlineTime) || 0
        // 总空闲时长
        let idleSum = Number(statusTime.AllIdleTime) || 0
        let busyNum = statusTime.BusyNum || 0
        let vacaNum = statusTime.VacaNum || 0
        if (onePeer.login) {
          if (onePeer.busyType !== '0' && onePeer.busyType !== '2') {
            // 忙碌
            busySum += timeDiff
          }
          if (onePeer.busyType === '2') {
            // 小休
            restSum += timeDiff
          }
          if (onePeer.login) {
            // 在线
            onlineSum += timeDiff
          }
          if (onePeer.busyType === '0') {
            // 空闲
            idleSum += timeDiff
          }
        }
        let allBusyTime = showCountDown(busySum)
        let allVacaTime = showCountDown(restSum)
        let allOnlineTime = showCountDown(onlineSum)
        let allIdleTime = showCountDown(idleSum)
        let dealingTime = showCountDown(onePeer.DialoutTimeLength)
        let queueName = onePeer.queueName ? onePeer.queueName : ''
        let customerNo = checkHideTel(onePeer.callNo, this.$store.state.session.user)
        let answerCount = onePeer.InComplete
        let dealingCount = onePeer.OutCalls
        let dealingSuccessCount = onePeer.OutComplete
        let buttonState = ctiUicontrolMonitor(onePeer, phoneData, this.$store.state) || {}
        let operate = {channel: onePeer.channel, userId: userId, pbx: onePeer.pbx, linkedChannel: onePeer.linkedChannel, buttonState: buttonState}
        let stateTimeNum = ''
        let stateTime = ''
        let condition = onePeer.login && onePeer.timestamp
        if (flag !== 'create') {
          condition = onePeer.extenType && onePeer.timestamp
        }
        if (condition) {
          var identity = date.valueOf()
          var oldTime = ((identity - phoneData.currentServerTime) - parseFloat(onePeer.timestamp) * 1000) / 1000
          if (oldTime < 0) {
            oldTime = 0
          }
          stateTimeNum = oldTime
          stateTime = showCountDown(oldTime * 1000)
        } else {
        }
        return {
          userId: userId,
          register: onePeer.register,
          login: onePeer.login,
          version: onePeer.version,
          busyType: onePeer.busyType,
          allBusyTime,
          allVacaTime,
          allOnlineTime,
          allIdleTime,
          busySum,
          restSum,
          onlineSum,
          idleSum,
          busyNum,
          vacaNum,
          DealingTime: dealingTime,
          agentName,
          agentNo,
          answerStyle,
          state,
          stateTimeNum,
          stateTime,
          dealingTime,
          queueName,
          customerNo,
          answerCount,
          dealingCount,
          dealingSuccessCount,
          operate,
          sensitiveWord: onePeer.sensitive,
          sensitiveAgent: onePeer.sensitiveAgent || '',
          sensitiveCustomer: onePeer.sensitiveCustomer || ''
        }
      },
      timeChange () {
        let self = this
        this.timer = window.setInterval(function () {
          for (let i = 0; i < self.monitorPeerDisplay.length; i++) {
            let onePeer = self.monitorPeerDisplay[i]
            if (onePeer.stateTimeNum !== '') {
              onePeer.stateTime = showCountDown((onePeer.stateTimeNum++) * 1000)
            }
            if (onePeer.login) {
              if (onePeer.busyType !== '0' && onePeer.busyType !== '2') {
                // 忙碌
                onePeer.allBusyTime = showCountDown(onePeer.busySum += 1000)
              }
              if (onePeer.busyType === '2') {
                // 小休
                onePeer.allVacaTime = showCountDown(onePeer.restSum += 1000)
              }
              if (onePeer.login) {
                // 在线
                onePeer.allOnlineTime = showCountDown(onePeer.onlineSum += 1000)
              }
              if (onePeer.busyType === '0') {
                // 空闲
                onePeer.allIdleTime = showCountDown(onePeer.idleSum += 1000)
              }
            }
          }
        }, 1000)
      },
      close (data) {
        this.isShow = false
        if (data === 'save') {
          this.$store.dispatch('getReportTableHeader', 'im_monitor_agent_call').then((res) => {
            res.Config.splice(0, 4)
            this.headOptionsShow = res
          })
        }
      },
      phoneBarStatusArr (flag) {
        let busyTypeName = this.$store.state.cti.globalLet.busyTypeName
        let phoneBarStatus = [{key: '', value: this.$t('public.all')}]
        for (let key in busyTypeName) {
          if (key !== '99') {
            let tempPhoneBarStatus = {key: busyTypeName[key], value: busyTypeName[key]}
            phoneBarStatus.push(tempPhoneBarStatus)
          }
        }
        let obj1 = {key: this.$t('monitor.online'), value: this.$t('monitor.online')}
        // 从cti中国际化，勿变
        let obj2 = {key: this.$t('cti.ready'), value: this.$t('cti.ready')}
        let obj3 = {key: this.$t('cti.offline'), value: this.$t('cti.offline')}
        phoneBarStatus.push(obj1)
        if (flag === 'all') {
          phoneBarStatus.push(obj2)
          phoneBarStatus.push(obj3)
        }
        return phoneBarStatus
      },
      fetchData () {
        let phonePeer = window.phone_peers
        this.$store.commit('AGENT_STATE_CHANGE', 'deleteTemp')
        this.monitorPeerDisplay = []
        // 取数据权限
        this.scope = this.scopeAgents()
        for (var n in phonePeer) {
          if (this.scope === 'noScope') {
            this.$set(this.monitorPeerDisplay, this.monitorPeerDisplay.length, this.monitorPeerNew(null, phonePeer[n], 'create', n))
            // this.monitorPeerDisplay.push(this.monitorPeerNew(null, phonePeer[n], 'create', n))
          } else {
            if (this.scope.indexOf(n) !== -1) {
              // this.monitorPeerDisplay.push(this.monitorPeerNew(null, phonePeer[n], 'create', n))
              this.$set(this.monitorPeerDisplay, this.monitorPeerDisplay.length, this.monitorPeerNew(null, phonePeer[n], 'create', n))
            }
          }
        }
        this.monitorSearch()
      }
    },
    beforeMount () {
      let agents = getCache('agents') || []
      // 筛选出未停用座席
      this.allAgent = agents.filter((item) => {
        if (item.status !== 'disable') {
          return true
        } else {
          return false
        }
      })
      this.fetchData()
      this.fetchQueuesData()
      this.phoneServiceNosData()
      this.timeChange()
      this.close('save')
      this.$store.dispatch('getConcurrent').then(() => {
        this.$data.concurrent = this.$store.state.cti.globalLet.limits
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../assets/common.styl';
  .wrap
    padding 0 15px 80px
    overflow auto
    .con
      width 100%
      margin 0 auto
      .el-table
        width 100%
    .Seats
      margin 0 auto
      .el-table
        width 100%
        overflow visible
      .el-row
        height 48px
        border 1px solid #dedede
        border-bottom none
        padding 8px 0 0 20px
        line-height 24px
      .agnet-search
        border none
    .tip
      height 48px
      border 1px solid #dedede
      border-bottom none
      padding-left 20px
      line-height 48px
      .concurrent-num
        display inline-block
        width 20px
        height 20px
        background #7cccd3
        text-align center
        line-height 20px
        margin-left 8px
        border-radius 10px
  .el-table
    width 100%
    margin 0 auto
    td
      .cell
        color $cf-gray1
  .checkbox-wrap
    padding 4px 0 0 10px
  .search-label
    padding 4px 0px 0 0
  .record-num
    line-height 24px
    padding-right 20px
    text-align right
  .config
    padding 6px 0 0 0
    .tex
      margin-left 10px
      position relative
      top -2px
      cursor pointer
      &:hover
        color $c-main
    .iconfont
      fontSize 18px
      color $c-main
  .title
      color $cf-gray0
      margin 28px 0 18px 0
      font-weight normal
      position relative
      .sign
        position relative
        width 12px
        height 12px
        background #7ccdd1
        display inline-block
        z-index 3
      .text
        position relative
        display inline-block
        padding 0 8px 0 10px
        background #fff
        z-index 3
      &:after
        content ""
        display inline-block
        width 100%
        left 0
        border-bottom 1px dashed #a6a6a6
        position absolute
        top 12px
  .phone-state
    position relative
  .moniter-dialog
    padding 10px
    .dialog-title
      font-size 14px
      padding 15px 0
  tbody
    td
      padding-left 18px
      padding-right 18px
  .tips
    padding-top 20px
    color #00c7d1
</style>
